const CabinetServices = require('../services/cabinetServices')

class CabinetControllers {
  constructor() {
    // bind 是 JavaScript 中的一个方法，用于创建一个新函数，并将 this 绑定到指定的对象
    // 这里的 this 是当前实例 而不是上下文 this
    this.addNewCabinet = this.addNewCabinet.bind(this)
    this.delCabinetByNum = this.delCabinetByNum.bind(this)
    this.updateCabinetByNum = this.updateCabinetByNum.bind(this)
    this.getAllCabinets = this.getAllCabinets.bind(this)
    this.getCabinetByNum = this.getCabinetByNum.bind(this)
    this.getCabinetsByGrpId = this.getCabinetsByGrpId.bind(this)
    this.closeCabinetByNum = this.closeCabinetByNum.bind(this)
  }

  // 统一响应函数
  handleRequest = async (serviceMethod, req, res, successStatus = 200) => {
    try {
      const result = await serviceMethod(req)
      if (result.code === 0) {
        res.status(successStatus).json(result) // 成功
      } else {
        res.status(result.statusCode || 400).json(result) // 失败
      }
    } catch (error) {
      console.log(error)
      res.status(500).json({
        code: 1,
        msg: '服务器内部错误',
      })
    }
  }

  async addNewCabinet(req, res) {
    await this.handleRequest(
      () => CabinetServices.addNewCabinet(req.body),
      req,
      res
    )
  }

  async delCabinetByNum(req, res) {
    await this.handleRequest(
      () => CabinetServices.delCabinetByNum(req.params.number),
      req,
      res
    )
  }

  async updateCabinetByNum(req, res) {
    await this.handleRequest(
      () => CabinetServices.updateCabinetByNum(req.params.number, req.body),
      req,
      res
    )
  }

  async getCabinetByNum(req, res) {
    await this.handleRequest(
    () => CabinetServices.getCabinetByNum(req.params.number),
    req,
    res
    )
  }

  async getCabinetsByGrpId(req, res) {
    await this.handleRequest(
    () => CabinetServices.getCabinetsByGrpId(req.params.grpid),
    req,
    res
    )
  }

  async getAllCabinets(req, res) {
    await this.handleRequest(
    () => CabinetServices.getAllCabinets(),
    req,
    res
    )
  }
  /* 修改快递柜门的状态 _ 开关门 */
  async closeCabinetByNum(req, res) {
    const { belong, number } = req.body
    await this.handleRequest(
      () => CabinetServices.closeCabinetByNum(belong, number),
      req,
      res
    );
  }
}

module.exports = new CabinetControllers